package main

import (
	"fmt"
	"log"

	"github.com/PuerkitoBio/goquery"
	"github.com/hu17889/go_spider/core/common/page"
	"github.com/hu17889/go_spider/core/common/request"
	"github.com/hu17889/go_spider/core/spider"
)

type Series struct {
	crawler             *spider.Spider
	reqs, processorReqs []*request.Request
}

func NewSeries(reqs []*request.Request) *Series {
	return &Series{
		crawler: spider.NewSpider(&Series{}, "Series"),
		reqs:    reqs,
	}
}

func (t *Series) Run() {
	log.Print("获取 Intel 处理器各系列下的处理器列表...")
	t.crawler.SetSleepTime("rand", 500, 2000).GetAllByRequest(t.reqs)
}

func (t *Series) Process(p *page.Page) {
	if !p.IsSucc() {
		log.Printf("Url: %s, Err: %s", p.GetRequest().Url, p.Errormsg())
		return
	}

	q := p.GetHtmlParser()

	q.Find(".add-compare-wrap a").Each(func(i int, s *goquery.Selection) {
		url := fmt.Sprintf("https://ark.intel.com%+v", s.AttrOr("href", ""))

		log.Printf("%s %s", s.Text(), url)
		t.processorReqs = append(t.processorReqs, request.NewRequest(url, "html", s.Text(), "GET", "", nil, nil, nil, nil))
	})
}

func (t *Series) Finish() {
	log.Print("Intel 处理器各系列下的处理器列表已解析完毕！！！")
	NewProcessor(t.processorReqs).Run()
}
